//################################
// 版权所有：中国农业银行软件开发中心
// 系统名称：移动办公应用-手机版
// 文件名称：pandaTextInput.js
// 创建时间：2016年10月14日
// 创建人员：Panda
// 功能说明：带下拉菜单的文本输入框
//################################

'use strict';

import React, {Component} from 'react';
import {
    Text,
    TouchableOpacity,
    StyleSheet,
    View,
    Dimensions,
    Image,
} from 'react-native';

import {
    Colors,
    FontSizes,
} from '../../common';

import Images from '../../images';

import Modal from '../modal';
import Button from '../button';

import Icon from 'react-native-vector-icons/EvilIcons';
import reactMixin from 'react-mixin';
import TimerMixin from 'react-timer-mixin';
// import TextInput from 'react-native-autocomplete-input';
import TextInput from './autoComplete';

const WINDOW_WIDTH = Dimensions.get('window').width;
const WINDOW_HEIGHT = Dimensions.get('window').height;

class PandaTextInput extends Component {
    constructor(props) {
        super(props);

        this.data = props.data;
        this.plocation = props.plocation;

        this.isModalOpen = false;
        this.value = '';

        this.changeTextTimer = null;

        this.state = {
            isOpen: false,
            buttonHeight: 0,
            isBackgroundTransparent: true,
        };
    }

    componentWillReceiveProps(nextProps) {
        // this.data = [];
        // this.setState({});
        this.data = nextProps.data;
        this.searchData = nextProps.searchData;
        // if (this.searchData && this.searchData.length === 1) {
        //     this.addItem(this.searchData[0]);
        // }
        this.plocation = nextProps.plocation;
        this.setState({});
    }
    
    openModal() {
        this.value = '';
        this.searchData = [];
        this.textInput && this.textInput.isOverlayShow(false);
        this.isModalOpen = true;
        this.setState({
            isOpen: true,
        });
    }

    closeModal() {
        this.value = '';
        this.searchData = [];
        this.textInput && this.textInput.isOverlayShow(false);
        this.isModalOpen = false;
        this.props.modalClosed && this.props.modalClosed();
        this.setState({
            isOpen: false,
        });
        
    }

    isShown() {
        // this.setState({
        //     isOpen: false,
        // });
        // this.state.isOpen = false;
        return this.isModalOpen;
    }

    setIsModalOpenState(isModalOpen) {
        this.isModalOpen = isModalOpen;
        if (!isModalOpen) {
            this.value = '';
            this.searchData = [];
            this.textInput && this.textInput.isOverlayShow(false);
            this.props.modalClosed && this.props.modalClosed();
        }
        this.setState({
            isOpen: false,
        });
    }

    focus() {
        this.value = '';
        this.textInput && this.textInput.focus && this.textInput.focus();
    }

    blur() {
        this.value = '';
        this.searchData = [];
        this.textInput && this.textInput.isOverlayShow(false);
        this.setState({});
        this.textInput && this.textInput.blur && this.textInput.blur();
    }

    onButtonPress() {
        this.addContact();
    }

    addContact() {
        if (this.value === '') {
            this.closeModal();

            return;
        }

        // alert(this.inputText);
        let validateResult = this.props.validateText && this.props.validateText(this.value);

        if (validateResult) {
            this.textInput && this.textInput.isOverlayShow(false);
            this.searchData = [];
            this.setState({isBackgroundTransparent: true});

            //验证通过，同步数据
            this.props.syncData && this.props.syncData(this.value);
            // this.inputText = '';
            this.value = '';
            // this.setState({});
            this.textInput && this.textInput.textInput && this.textInput.textInput.setNativeProps({text: ''});
        }
    }

    onChangeText(text) {
        if (this.changeTextTimer !== null) {
            clearTimeout(this.changeTextTimer);
        }
        // this.inputText = text;
        this.value = text.trim();
        // this.setState({});

        if (this.value.length > 0) {
            this.textInput && this.textInput.isOverlayShow(true);
            // if (this.value.length < 2 && this.searchData.length > 0) {
            //     this.searchData = [];
            // }
            if (this.value.length < 2) {
                this.searchData = [];
            }
            this.setState({
                isBackgroundTransparent: false,
            });

            if (this.value.length >= 2) {
                if (this.value.indexOf('@') >= 0) {
                    // 用户自己输入邮箱地址
                    this.changeTextTimer && clearTimeout(this.changeTextTimer);
                }
                else {
                    this.changeTextTimer = this.setTimeout(() => {
                        this.props.searchCallback && this.props.searchCallback(this.value);
                    }, 1000);
                }
            }
        }
        else {
            this.textInput && this.textInput.isOverlayShow(false);
            this.searchData = [];
            this.setState({
                isBackgroundTransparent: true,
            });
        }
        
        
    }

    setIndicatorShow(isIndicatorShown) {
        this.textInput && this.textInput.setIndicatorShow(isIndicatorShown);
    }

    onDeleteItem(item) {
        this.props.deleteItem && this.props.deleteItem(item);
    }

    addItem(item) {
        let validateResult = this.props.validateText && this.props.validateText(item);

        if (validateResult) {
            this.value = '';
            this.textInput && this.textInput.isOverlayShow(false);
            this.searchData = [];
            this.setState({isBackgroundTransparent: true});
            this.props.syncData && this.props.syncData(item);
        }
    }

    clearOnOneSearchResult() {
        this.value = '';
        this.textInput && this.textInput.isOverlayShow(false);
        this.searchData = [];
        this.setState({isBackgroundTransparent: true});
    }

    isModule(name) {
        return this.props.module && this.props.module === name;
    }
    
    //<Modal isOpen={this.state.isOpen} style={{position: 'absolute',}} backdropClose={(isModalOpen) => {this.setIsModalOpenState(isModalOpen)}} backdropPressToClose={this.state.isBackgroundTransparent} isBackdropColorTransparent={this.state.isBackgroundTransparent} cannotBeClosedOnBack={false}>
    render() {
        return (
            <Modal isOpen={this.state.isOpen} style={{position: 'absolute',}} backdropClose={(isModalOpen) => {this.setIsModalOpenState(isModalOpen)}} backdropPressToClose={true} isBackdropColorTransparent={false} cannotBeClosedOnBack={false}>
                <View style={styles.container}>
                    <View
                        ref={(ref) => {this.textinputView = ref}}
                        style={[{top: this.plocation.top, left: this.plocation.left, width: this.plocation.width}]}
                        >
                        <TextInput
                            ref={(ref) => {this.textInput = ref}}
                            containerStyle={[styles.textinputouttercontainer, {opacity: 1, }]}
                            inputContainerStyle={[styles.textinputinnercontainer,{ width: this.plocation.width}]}
                            listStyle={{width: this.plocation.width - 2,}}
                            autoCapitalize={'none'}
                            autoCorrect={false}
                            data={this.data}
                            returnKeyType={'done'}
                            onSubmitEditing={(e) => {this.addContact()}}
                            onChangeText={(text) => {this.onChangeText(text)}}
                            defaultValue={this.value}
                            renderItem={(item) => {
                                if (this.isModule('COOP')) {
                                    return (
                                        <View style={[styles.item, {backgroundColor: Colors.appBackground}]}>
                                            <Text style={styles.itemtext}>{item.name + ' - ' + item.orgShort}</Text>
                                            <TouchableOpacity style={styles.deletebutton} onPress={()=>{this.onDeleteItem(item)}}>
                                                <Icon style={styles.deleteicon} name={'minus'} size={28} color={Colors.attachmentIcon} />
                                            </TouchableOpacity>
                                        </View>
                                    );
                                }
                                else {
                                    return (
                                        <View style={[styles.item, {backgroundColor: Colors.appBackground}]}>
                                            <Text style={styles.itemtext}>{item}</Text>
                                            <TouchableOpacity style={styles.deletebutton} onPress={()=>{this.onDeleteItem(item)}}>
                                                <Icon style={styles.deleteicon} name={'minus'} size={28} color={Colors.attachmentIcon} />
                                            </TouchableOpacity>
                                        </View>
                                    );
                                }
                            }}
                            onLayout={() => {
                                this.textInput.textInput && this.textInput.textInput.measure((ox, oy, width, height, px, py) => {
                                    this.setState({
                                        buttonHeight: height,
                                    });
                                });
                            }}
                            searchData={this.searchData}
                            searchListStyle={{width: this.plocation.width - 2,}}
                            renderSearchItem={(item) => {
                                if (this.isModule('COOP')) {
                                    return (
                                        <TouchableOpacity style={styles.itemrow} onPress={() => {this.addItem(item)}}>
                                            <View key={item.cardId} style={styles.coopcontentbody}>
                                                <Text style={styles.coopcontenttext}>{item.name}</Text>
                                                <Text style={styles.subTitle}>{item.orgShort}</Text>
                                            </View>
                                        </TouchableOpacity>
                                    );
                                }
                                else {
                                    return (
                                        <TouchableOpacity style={[styles.item, {backgroundColor: Colors.appBackground}]} onPress={() => {this.addItem(item)}}>
                                            <Text style={styles.itemtext}>{item}</Text>
                                        </TouchableOpacity>
                                    );
                                }
                            }}
                        />
                        
                    </View>

                    {
                        this.isModule('COOP') ?
                        null
                        :
                        <TouchableOpacity onPress={() => {this.onButtonPress()}} style={{top: this.plocation.top, left: this.plocation.left + 4, height: this.state.buttonHeight}}>
                            <Image source={Images.EmailAddContacts} style={{width: this.state.buttonHeight, height: this.state.buttonHeight}} resizeMode={Image.resizeMode.contain} />
                        </TouchableOpacity>
                    }
                    
                </View>
            </Modal>
        );
    }
}

reactMixin(PandaTextInput.prototype, TimerMixin);


                    // <View style={[styles.buttonview, {top: this.plocation.top + 6, left: this.plocation.left + 2, }]}>
                    //     <Button text={'确定'} onPress={() => {this.onButtonPress()}} style={[styles.button,{height: this.state.buttonHeight}]} textStyle={styles.buttontext} />
                    // </View>
     
    //  listStyle={[styles.liststyle, {top: 1, left: 1, width: this.plocation.width - 2}]}
     
                        // onLayout={(event) => {
                        //     this.textinputView.measure((ox, oy, width, height, px, py) => {
                        //         this.buttonTop = py;
                        //         this.buttonLeft = px + width;
                        //         this.buttonHeight = height;

                        //         this.setState({});
                        //     })
                        // }}

const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        // width: WINDOW_WIDTH,
        // height: WINDOW_HEIGHT,
        // position: 'absolute',
        top: -(WINDOW_HEIGHT / 2),
        // left: -(WINDOW_WIDTH / 2),
        // bottom: 0,
        // right: 0,
        // height: WINDOW_HEIGHT,
        flex: 1,
        // backgroundColor: 'rgba(255, 0, 0, 0.3)',
        // alignItems:'flex-start',
        // justifyContent: 'flex-start',
        // alignSelf: 'flex-start',
    },
    textinputouttercontainer: {
        // flex: 1,
        // borderWidth: 1,
        // borderColor: 'red',
        // height: 100,
    },
    textinputinnercontainer: {
        // flex: 1,
        // margin: 0,
    },
    liststyle: {
        // height: WINDOW_HEIGHT / 2,
    },
    item: {
        flex: 1,
        flexDirection: 'row',
        paddingTop: 8,
        paddingBottom: 8,
        borderBottomWidth: 0.4,
        borderBottomColor: 'gray',
        alignItems: 'center',
    },
    itemtext: {
        flex: 1,
        marginLeft: 12,
        color: 'black',
    },
    deletebutton: {
        
    },
    deleteicon: {

    },
    buttonview: {
        // flex: 1,
    },
    button: {
        // flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    buttontext: {
        marginLeft: 4,
        marginRight: 4,
    },
    itemrow: {
        height: 50,
        alignItems: 'stretch',
        backgroundColor: Colors.appBackground,
        borderBottomWidth:FontSizes.spliterWidth,
        borderBottomColor:Colors.lightGray,
         flexDirection: 'row',
        // flexWrap:'wrap',
    },
    coopcontentbody: {
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'flex-start',
        // paddingLeft: 12,
        // paddingRight: 12,
        marginTop: 2,
        marginBottom: 2,
    },
    coopcontenttext: {
        fontSize: FontSizes.emailcontact,
        color: Colors.emailcontact,
        marginLeft : 12,
        marginRight: 12,
        flexWrap:'wrap'
    },
    subTitle:{
        fontSize:11,
        marginLeft:12,
        marginRight: 12,
        marginTop:3,
    },
});

export default PandaTextInput;